//
//  AFHTTPData.m
//  WXOpenIMSampleRelease
//
//  Created by 中矿科技有限公司 on 16/7/4.
//  Copyright © 2016年 taobao. All rights reserved.
//

#import "AFHTTPData.h"
#import "AFNetworking.h"
#import "UserManager.h"



#define YYEncode(str) [str dataUsingEncoding:NSUTF8StringEncoding]
@implementation AFHTTPData

-(void)getDataWithUrl:(NSString *)strUrl onSuccess:(BSuccess)success onFailure:(BFailure)failure
{
    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
    manager.responseSerializer =[AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    //设置URl的请求头
    NSString *token =[NSString stringWithFormat:@"%@",[UserManager sharedInstance].token ];
    [manager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
//    NSString *userID =[NSString stringWithFormat:@"%@",[UserManager sharedInstance].Uid];
    
    NSString* thisVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"i%@",thisVersion] forHTTPHeaderField:@"VER"];
    
//    [manager.requestSerializer setValue:userID forHTTPHeaderField:@"UID"];
    
    [manager GET:strUrl parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        [AFHTTPData kickPlayer:dic];
        success(responseObject);

    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        failure(error);
    }];
    

}

-(void)postDataWithUrl:(NSString *)strUrl httpBobyData:(id)dictObj onSuccess:(BSuccess)success onFailure:(BFailure)failure
{

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
    //NSURL *url = [NSURL URLWithString:@"[JSON SERVER"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strUrl ]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];
    
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    [request setHTTPMethod:@"POST"];
    
    if (dictObj) {
        NSData *postData = [NSJSONSerialization dataWithJSONObject:dictObj options:0 error:nil];
        [request setHTTPBody:postData];
    }

    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!data) {
                return ;
            }
            
          // NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            
            if([(NSHTTPURLResponse*)response statusCode] == 200 || [(NSHTTPURLResponse*)response statusCode] == 500){
                success(data);
            }else{
                failure(error);
            }
            
        });
        
    }];
    [postDataTask resume];
}
-(void)postTokenDataWithUrl:(NSString *)strUrl httpBobyData:(id)dictObj onSuccess:(BSuccess)success onFailure:(BFailure)failure
{
    
#if 1
    NSString *token =[NSString stringWithFormat:@"%@",[UserManager sharedInstance].token ];
    NSString* thisVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
    //NSURL *url = [NSURL URLWithString:@"[JSON SERVER"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strUrl ]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];
    
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:token forHTTPHeaderField:@"Authorization"];
    [request setValue:thisVersion forHTTPHeaderField:@"VER"];
    [request setHTTPMethod:@"POST"];
    
    if (dictObj) {
        NSData *postData = [NSJSONSerialization dataWithJSONObject:dictObj options:0 error:nil];
        [request setHTTPBody:postData];
    }
    
    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!data) {
                return ;
            }
            
            // NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            
            if([(NSHTTPURLResponse*)response statusCode] == 200 || [(NSHTTPURLResponse*)response statusCode] == 500){
                success(data);
            }else{
                failure(error);
            }
            
        });
        
    }];
    [postDataTask resume];
#endif

   
    
}
-(void)postSessionDataWithUrl:(NSString *)strUrl  httpBoby:(id)obj onSuccess:(BSuccess)success onFailure:(BFailure)failure
{

    NSString *token =[NSString stringWithFormat:@"%@",[UserManager sharedInstance].token ];
    NSString* thisVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    
    NSError *error;
    //NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arrayFile options:NSJSONWritingPrettyPrinted error:&error];//此处data参数是我上面提到的key为"data"的数组
    // NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
    //NSURL *url = [NSURL URLWithString:@"[JSON SERVER"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strUrl ]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];
    
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:token forHTTPHeaderField:@"Token"];
    [request setValue:thisVersion forHTTPHeaderField:@"VER"];
    [request setHTTPMethod:@"POST"];
    
    NSData *postData = [NSJSONSerialization dataWithJSONObject:obj options:0 error:&error];
    [request setHTTPBody:postData];
    
    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!data) {
                return ;
            }
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            [AFHTTPData kickPlayer:dic];
            if ([dic[@"Status"] integerValue] == 10) {
                
            }else if([dic[@"Status"] integerValue] == 1){
                success(data);
            }else{
                failure(error);
            }
            
        });
        
        
    }];
    [postDataTask resume];
}
-(void)postSessionBodyDataWithUrl:(NSString *)strUrl  httpBobyImage:(id)images httpBobyDcit:(id)dictObj  onSuccess:(BSuccess)success onFailure:(BFailure)failure
{

    AFHTTPSessionManager *_sessionManager = [AFHTTPSessionManager manager];
    // 设置请求的超时时间
    _sessionManager.requestSerializer.timeoutInterval = 30.f;
    // 设置服务器返回结果的类型:JSON (AFJSONResponseSerializer,AFHTTPResponseSerializer)
    _sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/*", nil];
    
    [_sessionManager.requestSerializer setValue:[UserManager sharedInstance].token forHTTPHeaderField:@"Authorization"];
    
    [_sessionManager POST:strUrl parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if ([(NSArray *)images count] >0) {
            for (NSUInteger i = 0; i < [(NSArray*)images count]; i++) {
                // 图片经过等比压缩后得到的二进制文件
                NSData *imageData = UIImageJPEGRepresentation(images[i], 0.5);
                // 默认图片的文件名, 若fileNames为nil就使用
                
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat = @"yyyyMMddHHmmss";
                NSString *str = [formatter stringFromDate:[NSDate date]];
                NSString *imageFileName = [NSString stringWithFormat:@"%@%ld.%@",str,i,@"jpg"];
                
                [formData appendPartWithFileData:imageData
                                            name:@"img"
                                        fileName: imageFileName
                                        mimeType:@"image/jpg"];
            }
        }
        [dictObj enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            [formData appendPartWithFormData:YYEncode(obj) name:key];
        }];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic =[NSDictionary dictionaryWithDictionary:responseObject];
        [AFHTTPData kickPlayer:dic];
        if ([dic[@"Status"] integerValue] == 10) {
            
        }else{
            success(responseObject);
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
    

}
+ (void)kickPlayer:(NSDictionary *)dataDic
{
    //如果是后台返回的被踢掉的信息
    if ([dataDic[@"Status"] integerValue] == 10) {
        //则发送一个通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kickPlayer" object:dataDic];
    }
}







/**
 获取当前显示的视图

 @return 返回当前视图
 */
- (UIViewController *)getCurrentVC{
    
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal){
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows){
            if (tmpWin.windowLevel == UIWindowLevelNormal){
                window = tmpWin;
                break;
            }
        }
    }

    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;

    return result;
    
}
@end
